package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Override
    public ResponseResult login(AdUserDTO dto) {
        String name = dto.getName();
        String password = dto.getPassword();
        //检查数据
        if(StringUtils.isBlank(name)||StringUtils.isBlank(password)){
             CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码不能为空");
        }
        //检查用户是否存在
        AdUser adUser = this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, name));
        if(adUser==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名不存在");
        }
        //检查用户状态是否有效
        if(9!=adUser.getStatus().intValue()){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR,"用户状态异常");
        }
        //获取数据库中的密码
        String adUserPassword = adUser.getPassword();
        //MD5加密  加盐
        String dtoPassword = DigestUtils.md5DigestAsHex((password+adUser.getSalt()).getBytes(StandardCharsets.UTF_8));
        //判断密码是否正确
        if(!adUserPassword.equals(dtoPassword)){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误,请重新输入");
        }
        //更新最近登录时间
        adUser.setLoginTime(new Date());
        //更新数据库
        this.updateById(adUser);
        //颁发token
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        //封装返回结果
        AdUserVO adUserVO = new AdUserVO();
        BeanUtils.copyProperties(adUser,adUserVO);
        //返回结果
        Map map = new HashMap<>();
        map.put("token",token);
        map.put("user",adUserVO);
        return ResponseResult.okResult(map);
    }
}
